#include "Thread.h"

namespace MiniWindow
{
	Thread::Thread(DWORD threadId)
	{
		this->_handle = null;
		this->_threadProc = null;
		this->_maxStackSize = 0;
		this->_threadId = threadId;
		if (0 != this->_threadId)
		{
			this->_handle = OpenThread(THREAD_ALL_ACCESS, FALSE, this->_threadId);
		}
	}
	Thread::Thread(ThreadProc threadProc, int maxStackSize)
	{
		this->_handle = null;
		this->_threadId = 0;
		this->_threadProc = threadProc;
		this->_maxStackSize = maxStackSize;
	}
	Thread::~Thread()
	{
		if (null != this->_handle)
		{
			CloseHandle(this->_handle);
		}
	}

	bool Thread::Start(void * parameter)
	{
		if (!this->IsAlive())
		{
			this->_handle = CreateThread(null, this->_maxStackSize, this->_threadProc, parameter, 0, &(this->_threadId));
		}
		return (null != this->_handle);
	}
	bool Thread::Stop()
	{
		if (this->IsAlive())
		{
			return  (TRUE == TerminateThread(this->_handle, 0));
		}
		return true;
	}
	void Thread::Suspend()
	{
		if (!this->IsAlive())
		{
			return;
		}
		SuspendThread(this->_handle);
	}
	void Thread::Resume()
	{
		if (!this->IsAlive())
		{
			return;
		}
		ResumeThread(this->_handle);
	}
	bool Thread::IsAlive() const
	{
		if (null == this->_handle)
		{
			return false;
		}
		DWORD code;
		if (!GetExitCodeThread(this->_handle, &code))
		{
			return false;
		}
		return (STILL_ACTIVE == code);
	}

	HANDLE Thread::GetHandle() const
	{
		return this->_handle;
	}
	DWORD Thread::GetThreadId() const
	{
		return this->_threadId;
	}

	void Thread::Sleep(int milliseconds)
	{
		::Sleep(milliseconds);
	}
	void Thread::Exit()
	{
		::ExitThread(0);
	}
	void Thread::Quit()
	{
		::PostQuitMessage(0);
	}
}